﻿using System;
using RBOSS.Business.LoginModule;
using RBOSS.Business.Smtp;
using RBOSS.Utilities;

namespace RBOSS.WebUI
{
    public partial class ForgetPassword : System.Web.UI.Page
    {
        private readonly LoginSubSystem _loginSubSystem = new LoginSubSystem();
        private readonly RandomPasswordGenerator _randomPasswordGenerator = new RandomPasswordGenerator();

        protected void Page_Load(object sender, EventArgs e)
        {
                
        }

        protected void btnForgetPassword_OnClick(object sender, EventArgs e)
        {
            var emailAddressValid = _loginSubSystem.CheckEmailAddress(txtForgetPassword.Text);
            if (emailAddressValid)
            {
                var randomString = _randomPasswordGenerator.Generate(10);
                var encryptedPassword = RBOSSecurity.Encrypt(randomString);
                _loginSubSystem.UpdatePassword(txtForgetPassword.Text, encryptedPassword);
                FailureText.Text = "Password sent to " + txtForgetPassword.Text + " successfully.";
                ForgetPasswordMessage.Visible = true;
                SendEmail(randomString, txtForgetPassword.Text);
            }
            else
            {
                FailureText.Text = "Email doesnot exists in the system";
                ForgetPasswordMessage.Visible = true;
            }
            
        }

        private void SendEmail(string password, string emailToSend)
        {
            const string subject = "Forget Password";
            var content = "Your reset password is : " + password;
            string[] recipient = { emailToSend };
            const string @from = "rboss.noreply@gmail.com";
            SmtpMail.SendGmail(subject, content, recipient, from);
        }
    }
}